<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称进行查询" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="useFlag">
        <el-select v-model="queryParams.useFlag" placeholder="上架状态" clearable size="small" style="width: 240px">
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['cms:banner:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['cms:banner:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['cms:banner:remove']">删除</el-button>
      </el-col> -->
      <div class="top-right-btn">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
            <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
          </el-tooltip>
        </div>
      </el-row>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="位置" align="center" prop="location" :formatter="locationFormat" />
      <el-table-column label="类型" align="center" prop="bannerType" :formatter="typeFormat" />
      <el-table-column label="内容" align="center" prop="imgUrl" >
        <template slot-scope="scope">
        <el-image style="width: 60px; height: 40px"
          :src="scope.row.imgUrl">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="上下架" align="center" prop="useFlag">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.useFlag"
            :active-value="1"
            :inactive-value="0"
            @change="handleUseFlagChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['cms:banner:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['cms:banner:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改banner对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入banner名称" />
        </el-form-item>
        <el-form-item label="类型" prop="bannerType">
          <el-radio-group v-model="form.bannerType">
            <el-radio :label="1">图片</el-radio>
            <el-radio :label="2" v-if="form.location == 1 || form.location == 3 || form.location == undefined">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="位置">
          <el-select v-model="form.location" placeholder="请选择banner位置">
            <el-option :key="4" label="官网位置1" :value="4" v-if="form.bannerType != 2"></el-option>
            <el-option :key="2" label="官网位置2" :value="2" v-if="form.bannerType != 2"></el-option>
            <el-option :key="1" label="小程序资讯页" :value="1"></el-option>
            <el-option :key="3" label="小程序活动页" :value="3"></el-option>
            <!-- <el-option v-for="dict in locationOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="parseInt(dict.dictValue)"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="视频" prop="videoUrl" required v-if="form.bannerType == 2">
          <el-upload ref="videoUrl"
              action="#"
              :http-request="requestVideoUpload"
              :file-list="videoFileList"
              :before-upload="beforeVideoUpload"
              :on-remove="handleVideoRemove"
              :multiple="false"
              list-type="text">
            <el-button size="small">
              上传视频
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <div slot="tip" class="el-upload__tip">1，尺寸：此处可使用16*9比例的视频；2，时长：≤60s，建议30秒以内的视频</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl" required v-if="form.bannerType == 1">
          <el-upload ref="imgUrl"
              action="#"
              :http-request="requestUpload"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :multiple="false"
              list-type="picture">
            <el-button size="small">
              上传
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接URL" prop="linkUrl" v-if="form.bannerType == 1">
          <el-input v-model="form.linkUrl" placeholder="请输入链接URL" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="是否上架" prop="useFlag">
          <el-switch
              v-model="form.useFlag"
              :active-value='1'
              :inactive-value='0' >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listBanner,
    getBanner,
    delBanner,
    addBanner,
    updateBanner,
    exportBanner,
    changeUseFlag
  } from "@/api/cms/banner";
  import {
    upload
  } from "@/api/upload.js"

  export default {
    name: "Banner",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // banner表格数据
        bannerList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // banner位置，枚举字典
        locationOptions: [],
        fileList: [],
        videoFileList:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          useFlag: undefined,
        },
        // 表单参数
        form: {
          useFlag: '1',
          imgUrl: '',
          videoUrl:''
        },
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "banner名称不能为空",
            trigger: "blur"
          }],
          location: [{
            required: true,
            message: "banner位置，枚举不能为空",
            trigger: "blur"
          }],
          imgUrl: [{
            required: true,
            message: "图片不能为空",
            trigger: "blur"
          }],
          orderNum: [{
            required: true,
            message: "排序不能为空",
            trigger: "blur"
          }],
          useFlag: [{
            required: true,
            message: "是否上架不能为空",
            trigger: "blur"
          }]
        },
        //上传路径
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload"
      };
    },
    created() {
      this.getList();
      this.getDicts("cms_banner_location").then(response => {
        this.locationOptions = response.data;
      });
    },
    methods: {
      /** 查询banner列表 */
      getList() {
        this.loading = true;
        listBanner(this.queryParams).then(response => {
          this.bannerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // banner位置，枚举字典翻译
      locationFormat(row, column) {
        return this.selectDictLabel(this.locationOptions, row.location);
      },
      typeFormat(row, column){
        if(row.bannerType == 1){
          return "图片";
        }else if(row.bannerType == 2){
          return "视频";
        }else{
          return "未知";
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          name: undefined,
          location: undefined,
          imgUrl: undefined,
          videoUrl: undefined,
          orderNum: undefined,
          useFlag: '1'
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加banner";
        this.fileList = [];
        this.form.useFlag='1';
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.fileList = [];
        this.videoFileList = [];
        const id = row.id || this.ids
        getBanner(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改banner";
          if(response.data.imgUrl != null && response.data.imgUrl != ''){
            let urlArr = response.data.imgUrl.split("/");
            this.fileList = [{name:urlArr[urlArr.length-1],url:response.data.imgUrl}];
          }
          if(response.data.videoUrl != null && response.data.videoUrl != ''){
            let urlArr = response.data.videoUrl.split("/");
            this.videoFileList = [{name:urlArr[urlArr.length-1],url:response.data.videoUrl}];
          }
        });
      },
      // 上下架修改
      handleUseFlagChange(row) {
        let text = row.useFlag === 1 ? "上架" : "下架";
        this.$confirm('确认要"' + text + '""' + row.name + '"Banner吗?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return changeUseFlag(row.id, row.useFlag);
          }).then(() => {
            this.msgSuccess(text + "成功");
          }).catch(function() {
            row.useFlag = row.useFlag === 0 ? 1 : 0;
          });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateBanner(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                  this.fileList = [];
                  this.videoFileList = [];
                }
              });
            } else {
              addBanner(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                  this.fileList = [];
                  this.videoFileList = [];
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除banner编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBanner(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有banner数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBanner(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      },
      beforeUpload(file) {
        const isJPG = file.type.indexOf("image/") != -1;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      beforeVideoUpload(file){
        let _this = this;
        return new Promise(async function(resolve, reject) {
          let fileName = file.name || "";
          const isLt10M = file.size / 1024 / 1024 < 10;
          if (!isLt10M) {
            _this.$message.error('上传视频大小不能超过 10MB!');
            reject();
          }
          let ext = fileName.split(".")[fileName.split(".").length - 1];
          if (
              ext !== "avi" &&
              ext !== "mp4" &&
              ext !== "3gp" &&
              ext !== "mkv" &&
              ext !== "mpg" &&
              ext !== "mpeg" &&
              ext !== "ts" &&
              ext !== "rmvb" &&
              ext !== "wmv" &&
              ext !== "flv" &&
              ext !== "mov"
          ) {
              _this.$message.error("上传视频应为 avi/mp4/3gp/mkv/mpg/mpeg/ts/rmvb/wmv/flv/mov 格式!");
              reject();
            }else{
              // 获取视频第一帧画面
              // _this.loadVideo(file).then(videoElem => {
              //     const canvasElem = document.createElement("canvas");
              //     const { videoWidth, videoHeight } = videoElem;
              //     canvasElem.width = videoWidth;
              //     canvasElem.height = videoHeight;
              //     canvasElem
              //         .getContext("2d")
              //         .drawImage(
              //             videoElem,
              //             0,
              //             0,
              //             videoWidth,
              //             videoHeight
              //         );
              //     // 导出成blob文件
              //     canvasElem.toBlob(blob => {
              //         let formData = new FormData();
              //         formData.append("file", blob);
              //         formData.append("fileSavePath","/cms/banner");
              //         upload(formData).then(response => {
              //           if (response.code === 200) {
              //             _this.form.imgUrl = response.url;
              //             // this.fileList = [{name:response.fileName, url: response.url}];
              //           }else{
              //             _this.$message.error('上传视频图片失败！');
              //             reject();
              //           }
              //         });
              //     }, "image/png");
              // });
            }
            resolve();
        });
      },
      // 获取视频的尺寸，播放时长
      loadVideo(file) {
          return new Promise(function(resolve, reject) {
              const videoElem = document.createElement("video");
              const dataUrl = URL.createObjectURL(file);
              // 当前帧的数据是可用的
              videoElem.onloadeddata = function() {
                  resolve(videoElem);
              };
              videoElem.onerror = function() {
                  reject("video 后台加载失败");
              };
              // 设置 auto 预加载数据， 否则会出现截图为黑色图片的情况
              videoElem.setAttribute("preload", "auto");
              videoElem.src = dataUrl;
          });
      },
      requestVideoUpload(params){
        const file = params.file;

        let formData = new FormData();
        formData.append("file", file);
        formData.append("fileSavePath","/cms/banner");

        upload(formData).then(response => {
          if (response.code === 200) {
            this.form.videoUrl = response.url;
            // this.fileList = [{name:response.fileName, url: response.url}];
          }else{
            this.$message.error('上传视频失败！');
          }
        });
      },
      handleVideoRemove(file, fileList) {
        this.form.videoUrl = '';
      },
      requestUpload(params){
        const file = params.file;

        let formData = new FormData();
        formData.append("file", file);
        formData.append("fileSavePath","/cms/banner");

        upload(formData).then(response => {
          if (response.code === 200) {
            this.form.imgUrl = response.url;
            // this.fileList = [{name:response.fileName, url: response.url}];
          }else{
            this.$message.error('上传图片失败！');
          }
        });
      },
      handleRemove(file, fileList) {
        this.form.imgUrl = '';
      }
    }
  };
</script>
